package device;

import communication.Communicator;
import communication.definitions.DeviceType;
import communication.definitions.ReceivedFunction;
import communication.exceptions.InvalidArgumentsException;

/**
 * An <code>ADC</code> is an extension of the <code>Sensor</code> class. It
 * implements the various functions needed for communicating with the ADC on the
 * robot.
 * 
 * @author Peter Kalauskas
 */
public class ADC extends Sensor {
	protected static ReceivedFunction[] implementedFunctions = { ReceivedFunction.SET_VALUE };

	/**
	 * Creates a new ADC device attached to the specified channel on PORTA.
	 * 
	 * @param id
	 *            The channel on PORTA for which this ADC is on.
	 */
	public ADC(byte id, Communicator comm) {
		super(DeviceType.ANALOG_DIGITAL_CONVERTER, id, comm);
	}

	/**
	 * Gets the voltage of the ADC. This will not request an update and will
	 * only used the value which is already stored in the ADC.
	 * 
	 * @return the voltage reading on this ADC.
	 */
	public double getVoltage() {
		return getValue() * 5.0 / 1024.0;
	}

	// Example of how super.receiveFunction(f, args) should be used:
	// public void receiveFunction(ReceivedFunction f, byte[] args)
	// throws InvalidArgumentsException, InvalidFunctionException {
	// try {
	// super.receiveFunction(f, args);
	// } catch (InvalidFunctionException e) {
	// switch (f) {
	// default:
	// throw new InvalidFunctionException("Function " + f
	// + " is not implemented for device type " + getType());
	// }
	// }
	// }

	/**
	 * Sets the raw value of this adc. This expects a high byte in index 0 and a
	 * low byte in index 1 of the arguments.
	 * 
	 * @param args
	 *            the high and low byte
	 * @throws InvalidArgumentsException
	 *             if too many or few arguments are given.
	 */
	protected void setValue(byte[] args) throws InvalidArgumentsException {
		if (args.length < 2) {
			throw new InvalidArgumentsException(
					"Too few arguments given to SET_VALUE on " + getType());
		} else if (args.length > 2) {
			throw new InvalidArgumentsException(
					"Too many arguments given to SET_VALUE on " + getType());
		}
		byte highByte = args[0];
		byte lowByte = args[1];
		setValue(((highByte & 0xFF) << 8) + (lowByte & 0xFF));
	}
}
